﻿using System.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using OpenQuarters.WebQuarters.Core;

namespace OpenQuarters.WebQuarters.Providers.Email
{
    public class DotNet2 : IEmailProvider
    {
        /// <summary>
        /// Sends email using .net 2.0 architecture
        /// </summary>
        /// <param name="to">Semi-colon seperated list of recipient email addresses</param>
        /// <param name="from">Senders email address</param>
        /// <param name="cc">Semi-colon seperated list of carbon copy email addresses</param>
        /// <param name="bcc">Semi-colon seperated list of blind carbon copy email address</param>
        /// <param name="subject">Subject of email</param>
        /// <param name="body">Body content of email</param>
        /// <param name="isHtml">Determine whether email is HTML formatted</param>
        public void SendEmail(string to, string from, string cc, string bcc, string subject, string body, bool isHtml)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

            //create the mail message
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();

            //set the addresses
            mailMessage.From = new MailAddress(from);

            foreach (string toAddress in to.Split(';'))
            {
                mailMessage.To.Add(toAddress.Trim());
            }

            if (!string.IsNullOrEmpty(cc))
            {
                foreach (string ccAddress in cc.Split(';'))
                {
                    mailMessage.CC.Add(ccAddress.Trim());
                }
            }

            if (!string.IsNullOrEmpty(bcc))
            {
                foreach (string bccAddress in bcc.Split(';'))
                {
                    mailMessage.Bcc.Add(bccAddress.Trim());
                }
            }

            //set the content
            mailMessage.Subject = subject;
            mailMessage.Body = body;
            mailMessage.IsBodyHtml = isHtml;

            //send the message (SMTP details in web.config <system.net>)
            SmtpClient client = new SmtpClient();
            client.Send(mailMessage);
        }
    }
}
